package com.xrui.parser;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;

public class ParserTest {
    public static class ThrowExceptionErrorListener extends BaseErrorListener {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer,
                                Object offendingSymbol,
                                int line,
                                int charPositionInLine,
                                String msg,
                                RecognitionException e)
        {
            throw e;
        }
    }
    public static void main(String args[]){
        String exprStr1 = "(NULL+random())";
        String exprStr2 = "(random())";
        String exprStr3 = "( )";
        String exprStr4 = "NULL+random()";
        String exprStr5  = "";
        String exprStr6  = "11";
        String exprStr7  = "a11";
        String exprStr  = "a11 + random()";
        ExprSyntaxLexer lexer = new ExprSyntaxLexer(CharStreams.fromString(exprStr));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExprSyntaxParser parser = new ExprSyntaxParser(tokens);
        lexer.addErrorListener(new ThrowExceptionErrorListener());
        parser.addErrorListener(new ThrowExceptionErrorListener());
        try {
             ExprSyntaxParser.ExpressionContext exprCtx = parser.expression();

            if ( exprCtx.exception != null)
                throw exprCtx.exception;
            ParseTree tree = exprCtx;
            System.out.println("The lisp style ast of : " + exprStr);
            System.out.println(tree.toStringTree(parser));

            ASTEvaluator visitor = new ASTEvaluator();
            Object result = visitor.visit(tree);
            System.out.println("\nValue of : " + exprStr);
            System.out.println(result);
        }catch (Exception e){
            System.out.println("error");
        }
        //ExprSyntaxParser.ExpressionContext expressionContext =  parser.expression();
        //System.out.println(expressionContext.toStringTree());
    }
}
